package com.cqeec.myblog.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cqeec.myblog.model.Article;
import com.cqeec.myblog.model.DataDictionary;
import com.cqeec.myblog.service.ArticleService;
import com.cqeec.myblog.service.ArticleServiceImpl;

@WebServlet("/article/list.html")
public class ArticleListByTypeServlet extends HttpServlet {
	private static final long serialVersionUID = -6632599125425365734L;
	private int pageSize = 2;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type = req.getParameter("id"); // 文章分类的ID
		int curPageNumber;
		String page = req.getParameter("page");
		if (page == null || "".equals(page)) {
			curPageNumber = 1;
		} else {
			curPageNumber = Integer.parseInt(page);
		}
		ArticleService articleService = new ArticleServiceImpl();
		List<Article> list;
		int pages = 0; // 总页数
		try {
			// 根据文章的类型获取文章
			// list = articleService.getArticleByType(type);

			// 获取总页数
			int totalNumber = articleService.getRecordsTotalNumber(type);
			if (totalNumber % pageSize == 0) {
				pages = totalNumber / pageSize;
			} else {
				pages = totalNumber / pageSize + 1;
			}
			list = articleService.getArticleByPage(pageSize, curPageNumber, type);

			req.setAttribute("list", list);
			// 获取的文章类型
			List<DataDictionary> atList = articleService.getArticleType();
			req.setAttribute("atList", atList);

			req.setAttribute("type", type);
			req.setAttribute("pages", pages);
			req.setAttribute("curPage", curPageNumber);
			req.getRequestDispatcher("../type_article.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
